package com.itheima.auth;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

@Component
//除了登入外接口请求异常处理
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //验证为未登陆状态会进入此方法，认证错误
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String result = "{\n" +
                "\n" +
                "\"flag\":false,\n" +
                "\n" +
                "\"data\":\"\",\n" +
                "\n" +
                "\"message\":\""+authException.getMessage()+"\"\n" +
                "\n" +
                "}";
        printWriter.write(result);
        printWriter.flush();
    }
}
